<template>
	<div class="record">
		<van-sticky>
			<div class="select-box">
				<component
					:is="datePicker"
					v-model="filterData.date"
				/>
				<van-icon
					name="filter-o"
					@click="echoData.visible = true"
				/>
			</div>
		</van-sticky>

		<van-pull-refresh v-model="state.refresh" @refresh="onRefresh">
			<div class="total" v-if="state.total">{{ `共有${state.total}条记录` }}</div>
			<van-list
				:loading="state.loading"
				:finished="state.finished"
				:finished-text="state.list?.length !== 0 ? '———— 已经到底了哦 ————' : '' "
				@load="getList"
			>
				<div class="lists" v-if="state.list?.length">
					<component
						:is="recordItem"
						v-for="item in state?.list"
						:key="item.id"
						:details="item"
						@beforeLeave="beforeLeave"
						:date="filterData.date"
					/>
				</div>
				<component
					:is="empty"
					v-if="!state.list?.length && !state.loading"
				/>
			</van-list>
		</van-pull-refresh>

		<van-popup
			position="bottom"
			v-model:show="echoData.visible"
			round
			:close-on-click-overlay="false"
		>
			<div class="filter">
				<p @click="onFilterCancel">取消</p>
				<p>筛选</p>
				<p @click="onFilterConfirm">确认</p>
			</div>
			<van-form>
				<van-field
					label="行政区"
					v-model="echoData.countyName"
					placeholder="请选择"
					readonly
					is-link
					@click="changeRegion('county')"
				/>
				<van-field
					v-if="filterData.xzqdm"
					label="镇街"
					v-model="echoData.townshipName"
					placeholder="请选择"
					readonly
					is-link
					@click="changeRegion('township')"
				/>
				<van-field
					v-if="filterData.towndm"
					label="村"
					v-model="echoData.villageName"
					placeholder="请选择"
					readonly
					is-link
					@click="changeRegion('village')"
				/>
				<van-field
					label="房屋信息"
					v-model="filterData.text"
					placeholder="房屋编号，地址，户主姓名"
				/>
				<van-field
					label="隐患状态"
					readonly
				>
					<template #input>
						<van-radio-group v-model="filterData.pczt" direction="horizontal">
							<van-radio
								v-for="item in echoData.statusEnum"
								:name="item.value"
								:key="item.value"
							>
								{{ item.text }}
							</van-radio>
						</van-radio-group>
					</template>
				</van-field>
				<van-field
					label="自查状态"
					readonly
				>
					<template #input>
						<van-radio-group v-model="filterData.zczt" direction="horizontal">
							<van-radio
								v-for="item in echoData.zcEnum"
								:name="item.value"
								:key="item.value"
							>
								{{ item.text }}
							</van-radio>
						</van-radio-group>
					</template>
				</van-field>
				<van-field
					label="核验状态"
					readonly
				>
					<template #input>
						<van-radio-group v-model="filterData.jczt" direction="horizontal">
							<van-radio
								v-for="item in echoData.jcEnum"
								:name="item.value"
								:key="item.value"
							>
								{{ item.text }}
							</van-radio>
						</van-radio-group>
					</template>
				</van-field>
			</van-form>
		</van-popup>

		<van-popup v-model:show="echoData.regionVisible" position="bottom" round>
			<van-picker
				:columns="echoData[echoData.regionType]"
				@confirm="onConfirm"
				@cancel="echoData.regionVisible = false"
			/>
		</van-popup>
	</div>
</template>

<script setup>
import { reactive, nextTick, watch, onMounted } from 'vue'
import empty from '@/components/empty'
import { useLoginStore } from '@/store'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { getCheckRecordList, getRegion } from '@/service/village'
import recordItem from './components/recordItem'
import datePicker from '@/components/datePicker'

const loginStore = useLoginStore()
const { loginInfo } = storeToRefs(loginStore)

const filterData = reactive({
	xzqdm: '',
	towndm: '',
	villagedm: '',
	date: [],
	text: '',
	pczt: '0',
	zczt: '0',
	jczt: '0',
})
const echoData = reactive({
	visible: false,
	regionVisible: false,
	regionType: 'county',
	countyName: '',
	county: [],
	townshipName: '',
	township: [],
	villageName: '',
	village: [],
	statusEnum: [
		{ value: '0', text: '全部' },
		{ value: '1', text: '无隐患' },
		{ value: '2', text: '有隐患' },
	],
	zcEnum: [
		{ value: '0', text: '全部' },
		{ value: '1', text: '已自查' },
		{ value: '2', text: '未自查' },
	],
	jcEnum: [
		{ value: '0', text: '全部' },
		{ value: '1', text: '已核验' },
		{ value: '2', text: '未核验' },
	]
})
const state = reactive({
	loading: false,
	finished: false,
	refreshing: false,
	isEmpty: false,
	total: 0,
	page: 1,
	pageSize: 10,
	list: []
})

const onRefresh = () => {
	state.list = []
	state.page = 1
	state.refresh = false
	state.loading = false
	state.finished = true
	nextTick(() => {
		state.finished = false
	})
}

const getList = async () => {
	const params = {
		checktime: filterData.date,
		pageindex: state.page -  1,
		limit: state.pageSize,
		...filterData,
		pczt: +filterData.pczt,
		zczt: +filterData.zczt,
		jczt: +filterData.jczt,
	}
	try {
		state.loading = true
		const result = await getCheckRecordList(params)
		state.loading = false
		state.list = [...state.list, ...result.data.items]
		state.total = result.data.total
		if (state.page * state.pageSize >= state.total) {
			state.finished = true
		}
		state.page++
	} catch (err) {
		state.loading = false
		state.finished = true
	}
}

const onFilterConfirm = () => {
	echoData.visible = false
	onRefresh()
}

const onFilterCancel = () => {
	echoData.visible = false
	initFilteData()
	onRefresh()
}

const changeRegion = type => {
	const roleEnum = {
		2: ['county', 'township', 'village'],
		3: ['township', 'village'],
		4: ['village'],
	}
	if (roleEnum[loginInfo.value.roletype].includes(type)) {
		echoData.regionType = type
		nextTick(() => {
			echoData.regionVisible = true
		})
	}
}

const onConfirm = val => {
	echoData.regionVisible = false
	if (echoData.regionType === 'county') {
		echoData.countyName = val?.regionName
		filterData.xzqdm = val?.regionCode
		echoData.townshipName = ''
		filterData.towndm = ''
		echoData.villageName = ''
		filterData.villagedm = ''
		getRegionData(val?.regionCode, 'township')
	} else if (echoData.regionType === 'township') {
		echoData.townshipName = val?.regionName
		filterData.towndm = val?.regionCode
		echoData.villageName = ''
		filterData.villagedm = ''
		getRegionData(val?.regionCode, 'village')
	} else if (echoData.regionType === 'village') {
		echoData.villageName = val?.regionName
		filterData.villagedm = val?.regionCode
	}
}

const getRegionData = async (id, type) => {
	const result = await getRegion({
		parentid: id
	})
	if (result?.succ) {
		echoData[type] = result?.data?.map(item => {
			return {
				text: item.regionName,
				...item
			}
		})
	}
}

const initFilteData = () => {
	Object.keys(filterData).forEach(key => {
		filterData[key] = ''
	})
	filterData.date = []
	filterData.pczt = '0'
	filterData.zczt = '0'
	filterData.jczt = '0'
	filterData.xzqdm = loginInfo.value?.xzqdm
	filterData.towndm = loginInfo.value?.towndm
	filterData.villagedm = loginInfo.value?.villagedm
	echoData.countyName = loginInfo.value?.xzq
	echoData.townshipName = loginInfo.value?.town
	echoData.villageName = loginInfo.value?.village
}


const initQuery = () => {
	const filter = JSON.parse(sessionStorage.getItem('filterData'))
	Object.keys(filter)?.forEach(key => {
		filterData[key] = filter[key]
	})
	const echo = JSON.parse(sessionStorage.getItem('echoData'))
	Object.keys(echo)?.forEach(key => {
		echoData[key] = echo[key]
	})
	sessionStorage.removeItem('filterData')
	sessionStorage.removeItem('echoData')
	sessionStorage.removeItem('hasQuery')
}

const beforeLeave = () => {
	sessionStorage.setItem('filterData', JSON.stringify(filterData))
	sessionStorage.setItem('echoData', JSON.stringify(echoData))
	sessionStorage.setItem('hasQuery', 1)
}

onMounted(() => {
	if (sessionStorage.getItem('hasQuery')) {
		initQuery()
	} else {
		initFilteData()
		if ([2, 3, 4].includes(loginInfo.value?.roletype)) {
			getRegionData(
				loginInfo.value?.regionCode,
				loginInfo.value?.roletype === 2 ? 'county'
					: loginInfo.value?.roletype === 3 ? 'township'
						: loginInfo.value?.roletype === 4 ? 'village'
							: ''
			)
		}
	}
})

watch(() => filterData.date, () => {
	onRefresh()
}, { deep: true })

</script>

<style scoped lang="less">
.record {
	.select-box {
		display: flex;
		align-items: center;
		background: #fff;
		padding-right: 32px;
		i {
			font-size: 36px;
			color: var(--van-primary-color);
		}
	}
	:deep(.van-form) {
		.van-cell {
			.van-field__label {
				width: 160px;
			}
			.van-cell__value {
				.van-field__body {
					input {
						border: 0;
					}
				}
			}
		}
	}
	:deep(.date-picker) {
		flex: 1;
		border-radius: 8px;
		padding: 24px 32px;
		.date {
			background: #F6F7F8;
			border-radius: 16px;
		}
	}
	.filter {
		display: flex;
		padding: 32px;
		p {
			&:nth-of-type(1) {
				color: var(--time-color);
			}
			&:nth-of-type(2) {
				flex: 1;
				font-size: 32px;
				text-align: center;
			}
			&:nth-of-type(3) {
				color: var(--van-primary-color);
			}
		}
	}
	.total {
		height: 82px;
		line-height: 82px;
		text-align: center;
		color: #696969;
	}
}
</style>
